package com.sct.mycamapp;


import android.annotation.TargetApi;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sct.screen.Screen;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.List;


public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback, View.OnClickListener {
    private static final String mRcordFilePath = "/dev/null";
    private static final String TAG = "sct.java";

    private AudioTrack mAudioTrack = null;
    private PcmAudioRecorder mRecorder;

    private Camera mCamera;
    private byte[] mYUVData;
    private int mWidth;
    private int mHeight;
    private int mFps;

    private RelativeLayout mPreview;
    private RelativeLayout mGLView;
    private Button mBtnShow;
    private Button mBtnClose;
    private EditText mUrl;
    private TextView mInfo;
    private TextView mSzInfo;

    static {
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("sct");
        System.loadLibrary("camjni");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        SurfaceView sv = new SurfaceView(this);
        sv.getHolder().addCallback(this);

        mPreview = (RelativeLayout) findViewById(R.id.preview);
        mPreview.addView(sv);


        mFps = 25;
        mWidth = 320;
        mHeight = 240;

        GLSurfaceView view = new GLSurfaceView(this);
        view.setRenderer(new Screen(0));

        mGLView = (RelativeLayout) findViewById(R.id.glView);
        mGLView.addView(view);

        mBtnShow = (Button) findViewById(R.id.showButton);
        mBtnShow.setOnClickListener(this);
        mBtnClose = (Button) findViewById(R.id.closeButton);
        mBtnClose.setOnClickListener(this);

        mUrl = (EditText) findViewById(R.id.url);
        mInfo = (TextView) findViewById(R.id.info);
        mSzInfo = (TextView) findViewById(R.id.szInfo);

        int numberOfCameras = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                mCamera = Camera.open( i );
            }
        }

        if(null == mCamera)
        {
            mCamera = mCamera.open();
        }

        mRecorder = PcmAudioRecorder.getInstanse();
        mRecorder.setOutputFile(mRcordFilePath);

        int maxJitter = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
        mAudioTrack = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, 44100, AudioFormat.CHANNEL_OUT_STEREO,
                AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.showButton:
                Log.i(TAG, String.format("%s:%d", "show click", 100));
                CamJni.start(mUrl.getText().toString());
                break;

            case R.id.closeButton:
                Log.i(TAG, String.format("%s:%d", "close click", 2));
                CamJni.stop();
                break;

            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            mCamera.setPreviewDisplay(holder);
            Camera.Parameters parameters = mCamera.getParameters();

            List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
            List<Camera.Size> supportedPictureSizes = parameters.getSupportedPictureSizes();

            int sh = 10000;
            int sw = 10000;

            for (int i = 0; i<supportedPreviewSizes.size();i++)
            {

                if(supportedPreviewSizes.get(i).width < sw && supportedPreviewSizes.get(i).width >= 320)
                {
                    ///check if pic size support
                    for (int j = 0; j<supportedPictureSizes.size();j++)
                    {
                        if(supportedPictureSizes.get(j).width == supportedPreviewSizes.get(i).width &&
                                supportedPictureSizes.get(j).height == supportedPreviewSizes.get(i).height)
                        {
                            ///choose it
                            sw = supportedPreviewSizes.get(i).width;
                            sh = supportedPreviewSizes.get(i).height;
                        }
                    }

                }

            }

            Log.i("sct", String.format("choose size:%dx%d", sw, sh));
            mWidth = sw;
            mHeight = sh;

            mSzInfo.setText(String.format("size:%dx%d", sw, sh));

            mYUVData = new byte[mWidth * mHeight * 4];  ///YUV420

//            parameters.setFlashMode("off");
//            parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
//            parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
//            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            parameters.setPreviewFormat(ImageFormat.YV12);
            parameters.setPreviewFrameRate(mFps);

            int w = mWidth;
            int h = mHeight;

            parameters.setPictureSize(w, h);
            parameters.setPreviewSize(w, h);

            mCamera.setParameters(parameters);
            mCamera.addCallbackBuffer(mYUVData);
            mCamera.setPreviewCallbackWithBuffer(this);

            mRecorder.prepare();
            Log.i("sct", String.format(">>>>>>>>n:%d", mRecorder.getPeriodInFrames()));

            CamJni.create(w, h, mFps, mRecorder.getPeriodInFrames());
            mInfo.setText(CamJni.getURL());

            mCamera.startPreview();
            mRecorder.start();
            mAudioTrack.play();

            (new Thread(){
                @Override
                public void run() {
                    int len = 10000*4*2;
                    byte[] buf = new byte[len];
                    int offset = 0;
                    int n = 0;

                    while (true) {
                        if(0 == n)
                        {
                            n = CamJni.getpcmdata(buf, len);
                        }

                        mAudioTrack.write(buf, offset, n);
                        n = 0;
                    }
                }
            }).start();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCamera.startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    public double currentTime()
    {
        double d = System.currentTimeMillis();
        d /= 1000.0f;
        return d;
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        mCamera.addCallbackBuffer(mYUVData);

        CamJni.onFrame(data);
    }
}
